package com.bricker.laboratorymanagement.business.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bricker.laboratorymanagement.business.dao.ApprovalMapper;
import com.bricker.laboratorymanagement.business.dao.LaboratoryMapper;
import com.bricker.laboratorymanagement.business.dao.SysUserMapper;
import com.bricker.laboratorymanagement.business.entity.Approval;
import com.bricker.laboratorymanagement.business.entity.Message;
import com.bricker.laboratorymanagement.business.entity.SysGroup;
import com.bricker.laboratorymanagement.business.entity.SysUser;
import com.bricker.laboratorymanagement.business.model.AppSelectModel;
import com.bricker.laboratorymanagement.business.service.ApprovalService;
import com.bricker.laboratorymanagement.business.service.MessageService;
import com.bricker.laboratorymanagement.business.service.SysGroupService;
import com.bricker.laboratorymanagement.business.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApprovalServiceImpl extends ServiceImpl<ApprovalMapper, Approval> implements ApprovalService {
    @Autowired
    private SysGroupService sysGroupService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ApprovalMapper approvalMapper;

    @Autowired
    private LaboratoryMapper laboratoryMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Map<String,String> joinGroup(Long uId, Long groupId) {
        Map<String ,String> map =new HashMap<>();
        //查询当前用户是否有小组，或者已申请加入其他小组
        SysUser sysUser =sysUserService.getById(uId);
        Approval approvaByCurrent=super.getOne(Wrappers.<Approval>lambdaQuery()
                        .eq(Approval::getCreatedBy,uId)
                        .eq(Approval::getType,"0")
                        .eq(Approval::getState,"0")
                        .eq(Approval::getDelFlag,"0"));
        SysGroup sysGroup =sysGroupService.getById(groupId);
        String userIds=sysGroup.getUserIds();
        Integer currentsize=Arrays.asList(userIds.split(",")).size();
        if(sysUser.getGroupId()!=null && sysUser.getGroupId() != 0){
            map.put("code","0");
            map.put("message","您已存在小组");
        }else if(approvaByCurrent!=null){
            map.put("code","1");
            map.put("message","您已申请加入其它小组");
        }else  if(currentsize==sysGroup.getSize()){
            map.put("code","2");
            map.put("message","此小组已满员");
        } else {
            //获取小组长
            Long groupCreateBy= sysGroup.getCreatedBy();
            //创建审批流程
            Approval approval =new Approval();
            approval.setApplyId(groupId);
            approval.setType("0");
            approval.setState("0");
            approval.setReceiver("" + groupCreateBy);
            approval.setCreatedBy(uId);
            approval.setCreatedTime(LocalDateTime.now());
            approval.setDelFlag("0");
            super.save(approval);
            //像组长发送消息推送
            Message message =new Message();
            message.setContent(sysUser.getNickName()+"申请加入您的小组,请前往我的审批中进行处理");
            message.setCreatedTime(LocalDateTime.now());
            message.setReceivers(groupCreateBy+"");
            message.setStatus("0");
            message.setDelFlag("0");
            messageService.save(message);
            map.put("code","3");
            map.put("message","申请成功 ，等待审批");
        }
        return map;
    }

    @Override
    public Page<Approval> getApproval( AppSelectModel appSelectModel) {
        SysUser sysUser =sysUserService.getById(appSelectModel.getUId());
        Page<Approval> page =new Page<>(appSelectModel.getCurrent(),appSelectModel.getSize());
        List<Approval> list =null;
        if(sysUser.getUserType().equals("1")){
             list =approvalMapper.getApprovalByLeader(page,appSelectModel);
        }else {
            Approval app = new Approval();
            app.setReceiver("," + sysUser.getId() + ",");
            list = approvalMapper.getApprovalByAdmin(app);
        }
        return page.setRecords(list);
    }

    @Override
    public Map<String, String> updateStatus(Long uId,String state,Long id) {
        Map<String ,String> map=new HashMap<>();
        SysUser sysUser =sysUserService.getById(uId);
        SysGroup sysGroup =sysGroupService.getById(sysUser.getGroupId());
        Approval approval =super.getOne(Wrappers.<Approval>lambdaQuery()
                .eq(Approval::getId, id)
                .eq(Approval::getDelFlag, "0"));

        //获取申请用户
        Long userId=approval.getCreatedBy();
        SysUser appUser=sysUserService.getById(userId);
        //如果同意加入小组
        if(state.equals("2")){
            //先判断小组人数是否已满
            String userIds=sysGroup.getUserIds();
            Integer currentsize=Arrays.asList(userIds.split(",")).size();
            if(currentsize<sysGroup.getSize()){
                approval.setState("2");
                approval.setUpdatedBy(uId);
                approval.setUpdatedTime(LocalDateTime.now());
                approval.setDelFlag("1");
                super.updateById(approval);

                appUser.setGroupId(sysGroup.getId());
                sysUserService.updateById(appUser);
                //将此用户加入小组
                sysGroup.setUserIds(sysGroup.getUserIds()+","+appUser.getId());
                sysGroupService.updateById(sysGroup);
                //像用户发送消息
                Message message =new Message();
                message.setStatus("0");
                message.setContent(sysUser.getNickName()+"已同意您加入小组,请注意查看");
                message.setReceivers(appUser.getId()+"");
                message.setCreatedTime(LocalDateTime.now());
                message.setDelFlag("0");
                messageService.save(message);
                map.put("code","0");
                map.put("message","已同意此用户加入小组");
            }else {
                map.put("code","1");
                map.put("message","小组已满员");
            }
        }else {
            approval.setState("1");
            approval.setUpdatedBy(uId);
            approval.setUpdatedTime(LocalDateTime.now());
            approval.setDelFlag("1");
            super.updateById(approval);
            //像用户发送消息
            Message message =new Message();
            message.setStatus("0");
            message.setContent(sysUser.getNickName()+"未同意您加入小组,请注意查看");
            message.setReceivers(appUser.getId()+"");
            message.setCreatedTime(LocalDateTime.now());
            message.setDelFlag("0");
            messageService.save(message);
            map.put("code","2");
            map.put("message","已拒绝此用户加入小组");
        }

        return map;
    }

    @Override
    public Map<String, String> reserveLab(Long userId, Approval approval) {
        Map<String, String> map = new HashMap<>();
        if (approval != null) {
            SysUser sysUser = sysUserService.getById(userId);
            long applyId = approval.getApplyId();
            // 判断是否已有在途预约
            Approval result = approvalMapper.selectOne(Wrappers.<Approval>lambdaQuery()
                .eq(Approval::getCreatedBy, userId)
                .eq(Approval::getType, "1")
                .eq(Approval::getState, "3"));
            if (result != null) {
                map.put("code", "3");
                return map;
            }
            Date reserveStart = approval.getServeStartTime();
            Date reserveEnd = approval.getServeEndTime();
            // 查找该实验室所有预约记录
            List<Approval> approvals = approvalMapper.selectList(Wrappers.<Approval>lambdaQuery()
                .eq(Approval::getApplyId, applyId)
                .ne(Approval::getState, "1")
                .eq(Approval::getType, "1")); // 1代表实验室预约
            boolean isAllowReserve = approvals.stream().filter(e -> Objects.nonNull(e.getServeEndTime()) || Objects.nonNull(e.getServeStartTime()))
                .allMatch(e -> {
                    if (e.getServeEndTime().compareTo(reserveStart) == 0 && e.getServeStartTime().compareTo(reserveEnd) == 0) {
                        return false;
                    }else if (e.getServeEndTime().compareTo(reserveStart) <= 0 || e.getServeStartTime().compareTo(reserveEnd) >= 0) {
                        return true;
                    } else {
                        return false;
                    }
            }
            );
            if (isAllowReserve) {
                map.put("code", "0");
                approval.setCreatedBy(userId);
                approval.setUpdatedBy(userId);
                approval.setCreatedTime(LocalDateTime.now());
                approval.setUpdatedTime(LocalDateTime.now());
                approval.setServeStartTime(reserveStart);
                approval.setServeEndTime(reserveEnd);
                approval.setDelFlag("0");
                approval.setType("1");
                approval.setState("3");
                approval.setGroupId(sysUser.getGroupId());
                // 获取当前所有管理员
                List<SysUser> users = userMapper.selectList(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getUserType, "2")
                    .eq(SysUser::getDelFlag, "0"));
                List<Long> userIds = users.stream().map(e -> e.getId()).collect(Collectors.toList());
                String receiverIds = ",";
                for (Long id : userIds) {
                    receiverIds += (id + ",");
                }
                approval.setReceiver(receiverIds);
                approvalMapper.insert(approval);

                //管理员发送消息
                Message message =new Message();
                message.setStatus("0");
                message.setContent(sysUser.getNickName() + "申请使用实验室:" + approval.getLabName() + ",请尽快审批！");
                message.setReceivers(receiverIds);
                message.setCreatedTime(LocalDateTime.now());
                message.setDelFlag("0");
                messageService.save(message);
            } else {
                map.put("code", "1");
            }
        } else {
            map.put("code", "2");
        }
        return map;
    }

    @Override
    public Map<String, String> approvalReseve(Long uId, String state, Long id) {
        Map<String, String> map = new HashMap<>();
        String msgContent = "";
        SysUser sysUser =sysUserService.getById(uId);
        Approval approval =super.getOne(Wrappers.<Approval>lambdaQuery()
                .eq(Approval::getDelFlag, "0")
                .eq(Approval::getId, id));

        // 组长ID
        Long userId=approval.getCreatedBy();
        SysUser appUser=sysUserService.getById(userId);
        Approval app = new Approval();
        if ("2".equals(state)) {
            msgContent = "已同意实验室的使用";
            // 更新审批表状态
            map.put("code", "0");
            map.put("message", "已同意实验室的使用");
        } else {
            msgContent = "驳回了实验室的申请";
            map.put("code", "0");
            map.put("message", "已驳回实验室的使用");
        }
        app.setId(id);
        app.setState(state);
        app.setDelFlag("1");
        app.setUpdatedTime(LocalDateTime.now());
        app.setUpdatedBy(sysUser.getId());
        approvalMapper.updateById(app);
        //用户推送消息
        Message message =new Message();
        message.setStatus("0");
        message.setReceivers(appUser.getId() + "");
        message.setContent(sysUser.getNickName() + msgContent);
        message.setCreatedTime(LocalDateTime.now());
        message.setDelFlag("0");
        messageService.save(message);
        return map;
    }
}
